#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
mmqueue (mongodb message queue)
example:
    job = mmqueue.get(con.db.collection, block=True)
    with job:
        do_something_with(job)
    or
    job = mmqueue.get(con.db.collection, block=True)
    try:
        do_something_with(job)
    except:
        ...
    else:
        job.finish()
"""
from datetime import datetime, timedelta
import time


class Job(object):
    def __init__(self, collection, doc, time_field):
        self.collection = collection
        self.doc = doc
        self.time_field = time_field

    def __enter__(self):
        pass

    def __exit__(self, type, value, tb):
        if value is None:
            self.finish()

    def finish(self):
        if self.doc:
            self.collection.update({"_id": self.doc["_id"]}, {"$set": {self.time_field: datetime(9999, 1, 1)}})


def get(collection, time_field="_process", expire=60*10, query={}, block=False, interval=30):
    while True:
        update = {"$set": {time_field: datetime.now()}}
        query[time_field] = {"$lt": datetime.now()-timedelta(seconds=expire)}
        doc = collection.find_and_modify(query, update=update)
        if doc or (not block):
            return Job(collection, doc, time_field)
        time.sleep(interval)


def putMail(collection, from_addr, to_addrs, msg):
    doc = {
        "from_addr": from_addr,
        "to_addrs": to_addrs,
        "msg": msg,
        "_process": datetime(1000, 1, 1),
    }
    collection.insert(doc)


def putGtalkMsg(collection, msg, msg_to):
    doc = {
        "msg": msg,
        "msg_to": msg_to,
        "_process": datetime(1000, 1, 1),
    }
    collection.insert(doc)
